package com.hlhj.funlike_businessqzxd.Jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hlhj.funlike_businessqzxd.Event.JpushEvent;
import com.hlhj.funlike_businessqzxd.MyApp;
import com.hlhj.funlike_businessqzxd.R;
import com.hlhj.funlike_businessqzxd.activity.MainActivity;
import com.hlhj.funlike_businessqzxd.activity.OrderDetailAty;
import com.hlhj.funlike_businessqzxd.activity.SearchBTActivity;
import com.hlhj.funlike_businessqzxd.api.Apis;
import com.hlhj.funlike_businessqzxd.api.BaseObser;
import com.hlhj.funlike_businessqzxd.bean.OrderDetailBean;
import com.hlhj.funlike_businessqzxd.bean.PrintBean;
import com.hlhj.funlike_businessqzxd.data.OBean;
import com.hlhj.funlike_businessqzxd.data.SPUser;
import com.hlhj.funlike_businessqzxd.utils.Prints;
import com.lvrenyang.io.BTPrinting;
import com.lvrenyang.io.IOCallBack;
import com.lvrenyang.io.Pos;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.jpush.android.api.JPushInterface;

import static com.lzy.okgo.utils.HttpUtils.runOnUiThread;


/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver implements IOCallBack {
	private static final String TAG = "JIGUANG-Example";
	ExecutorService es = Executors.newScheduledThreadPool(30);

	boolean isOpen=false;
	@Override
	public void onReceive(final Context context, Intent intent) {
		try {
			Bundle bundle = intent.getExtras();
			Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

			if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
				String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
				Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
				//send the Registration Id to your server...

			} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
				Toast.makeText(context,"收到消息，不是推送",Toast.LENGTH_LONG).show();
				EventBus.getDefault().post(new JpushEvent());
				MediaPlayer player = MediaPlayer.create(context, R.raw.notice);
				player.start();

//				processCustomMessage(context, bundle);

			} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知"+ bundle.getString(JPushInterface.EXTRA_EXTRA));
				String orderStr = bundle.getString(JPushInterface.EXTRA_EXTRA);
				OBean oBean = new Gson().fromJson(orderStr, OBean.class);
				if (oBean.getType()==1){//新订单
					final Pos mPos = new Pos();
					final BTPrinting mBt = new BTPrinting();

					mPos.Set(mBt);
					mBt.SetCallBack(new IOCallBack() {
						@Override
						public void OnOpen() {
							Log.e("fhp","链接成功");
							isOpen=true;
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									final boolean bPrintResult = Prints.PrintTicket2(context, mPos, MainActivity.nPrintWidth, MainActivity.bCutter,
											MainActivity.bDrawer, MainActivity.bBeeper, MainActivity.nPrintCount, MainActivity.nPrintContent,
											MainActivity.nCompressMethod, MainActivity.bCheckReturn,sellerName,orderTime,goodsBean,
											packFee,sendFee,
											total,
											oriFee,
											addressBean,tel,payFee,cot,sName);
									Log.e("fhp","看下打印成功没"+bPrintResult);
								}
							});
						}

						@Override
						public void OnOpenFailed() {
							Log.e("fhp","链接失败");
							Toast.makeText(context,"链接打印机失败,请手动打印",Toast.LENGTH_SHORT).show();
						}

						@Override
						public void OnClose() {
							Log.e("fhp","链接关闭");
						}
					});

					Apis.INSTANCE.printInfo(oBean.getOrder_id())
							.subscribe(new BaseObser<Response<PrintBean>>(context) {
								@Override
								public void httpSuccess(Response<PrintBean> printBeanResponse) {
									try {
										PrintBean.DataBean printBean = printBeanResponse.body().getData();
										sellerName="";
										orderTime=printBean.getOrder_time();
										packFee="";
										sendFee="";
										total="";
										oriFee=printBean.getOriginal_price();
										tel=printBean.getMobile();
										payFee=printBean.getPrice();
										cot=printBean.getReduced_price();
										sName=printBean.getShop_name();
										addressBean=printBean.getAddress();
										goodsBean=printBean.getGoods();
										if (!SPUser.getBlueTag(context)){
											Intent it = new Intent(context, SearchBTActivity.class);
											it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
											it.putExtra("sellerName",sellerName);
											it.putExtra("orderTime",orderTime);
											it.putExtra("packFee","");
											it.putExtra("sendFee","");
											it.putExtra("total","");
											it.putExtra("oriFee",oriFee);
											it.putExtra("addressBean",addressBean);
											it.putExtra("tel",tel);
											it.putExtra("payFee",payFee);
											it.putExtra("cot",cot);
											it.putExtra("sName",sName);
											it.putExtra("type",2);//1-订单详情 -2推送
											context.startActivity(it);
//									it.putExtra("goodsBean",goodsBean);
										}else {
											Toast.makeText(context,"打印中请稍后",Toast.LENGTH_SHORT).show();
											if (isOpen){

												runOnUiThread(new Runnable() {
													@Override
													public void run() {
														final boolean bPrintResult = Prints.PrintTicket2(MyApp.context, mPos, MainActivity.nPrintWidth, MainActivity.bCutter,
																MainActivity.bDrawer, MainActivity.bBeeper, MainActivity.nPrintCount, MainActivity.nPrintContent,
																MainActivity.nCompressMethod, MainActivity.bCheckReturn,sellerName,orderTime,goodsBean,
																packFee,sendFee,
																total,
																oriFee,
																addressBean,tel,payFee,cot,sName);
														Log.e("fhp","看下打印成功没"+bPrintResult);
													}
												});
											}else {
												Log.e("fhp","链接蓝牙打印机"+SPUser.getBlue(context));
												new Thread(new Runnable() {
													@Override
													public void run() {
														mBt.Open(SPUser.getBlue(MyApp.context),MyApp.context);
													}
												}).start();
//											es.submit(new TaskOpen(mBt, SPUser.getBlue(context),context));
											}
										}
									}catch (Exception e){
										Log.e(TAG,"通过推送打印错误了");
										e.printStackTrace();
									}

								}
							});
					EventBus.getDefault().post("刷新一下");
					MediaPlayer player = MediaPlayer.create(context, R.raw.notice);
					player.start();
				}else {//退单
					EventBus.getDefault().post("刷新一下");
					MediaPlayer player = MediaPlayer.create(context, R.raw.cancel);
					player.start();
				}


			} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");
			} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
				Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
				//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

			} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
				boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
				Logger.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
			} else {
				Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
			}
		} catch (Exception e){

		}

	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
					Logger.i(TAG, "This message has no Extra data");
					continue;
				}

				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it =  json.keys();

					while (it.hasNext()) {
						String myKey = it.next();
						sb.append("\nkey:" + key + ", value: [" +
								myKey + " - " +json.optString(myKey) + "]");
					}
				} catch (JSONException e) {
					Logger.e(TAG, "Get message extra JSON error!");
				}

			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.get(key));
			}
		}
		return sb.toString();
	}
	private String sellerName,orderTime,packFee,sendFee,total,oriFee,tel,payFee,cot,sName,addressBean;
	public static List<PrintBean.DataBean.GoodsBean> goodsBean;
	@Override
	public void OnOpen() {

	}

	@Override
	public void OnOpenFailed() {
		Log.e("fhp","链接失败");
	}

	@Override
	public void OnClose() {
		Log.e("fhp","链接关闭");

	}

	public class TaskOpen implements Runnable
	{
		BTPrinting bt = null;
		String address = null;
		Context context = null;

		public TaskOpen(BTPrinting bt, String address, Context context)
		{
			this.bt = bt;
			this.address = address;
			this.context = context;
		}

		@Override
		public void run() {
			Log.e("fhp","准备链接打印机");
			// TODO Auto-generated method stub
			bt.Open(address,context);
		}
	}
}
